package com.caochenlei.codebuilder.config;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.caochenlei.codebuilder.utils.SystemUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class KVConfigUtil {
	private static Logger logger = LoggerFactory.getLogger(KVConfigUtil.class);

	/**
	 * 功能说明：读取配置文件
	 * 
	 * @param configName
	 * @return
	 */
	public static Map<String, String> read(String configName) {
		try {
			SAXReader saxReader = new SAXReader();
			Document document = null;
			try {
				document = saxReader.read(new BufferedReader(new InputStreamReader(new FileInputStream(SystemUtil.getConfigAbsolutePathByName(configName)), "UTF-8")));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			Element rootElement = document.getRootElement();

			logger.info("读取配置文件配置：" + configName);
			logger.info("读取配置文件路径：" + SystemUtil.getConfigAbsolutePathByName(configName));

			Map<String, String> map = new TreeMap<String, String>(new Comparator<String>() {
				@Override
				public int compare(String obj1, String obj2) {
					return obj1.compareTo(obj2);
				}
			});

			List<?> elements = rootElement.elements();
			for (int i = 0; i < elements.size(); i++) {
				Element element = (Element) elements.get(i);
				map.put(element.attributeValue("key"), element.attributeValue("value"));

				logger.info("读取配置文件参数：" + element.attributeValue("key") + " = " + element.attributeValue("value"));
			}

			return map;
		} catch (DocumentException e) {
			logger.error("读取配置文件失败：" + e.getMessage());
		}
		return null;
	}

	/**
	 * 功能说明：写入配置文件
	 * 
	 * @param configName
	 * @param map
	 */
	public static void write(String configName, Map<String, String> map) {
		Document document = DocumentHelper.createDocument();
		document.setRootElement(DocumentHelper.createElement(configName));

		for (String key : map.keySet()) {
			Element element = document.getRootElement().addElement("property");
			element.addAttribute("key", key);
			element.addAttribute("value", map.get(key));
		}

		XMLWriter writer = null;
		try {
			OutputFormat outputFormat = new OutputFormat();
			outputFormat.setEncoding("UTF-8");
			outputFormat.setNewlines(true);
			outputFormat.setNewLineAfterDeclaration(false);
			outputFormat.setIndent(true);
			outputFormat.setIndent("	");
			writer = new XMLWriter(new FileOutputStream(new File(SystemUtil.getConfigAbsolutePathByName(configName))), outputFormat);
			writer.write(document);
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("写入配置文件失败：" + e.getMessage());
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
